package com.lyj.ui.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lyj.pojo.User;
import com.lyj.service.UserService;
import com.lyj.service.impl.UserServiceImpl;

public class AutoLoginFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req= (HttpServletRequest) request;
		HttpServletResponse res= (HttpServletResponse) response;
		HttpSession session = req.getSession();
		
		UserService userService = new UserServiceImpl();
		
		if(session.getAttribute(User.SESSION_NAME) == null) {
			Cookie[] cookies = req.getCookies();
			if(cookies != null) {
				for(Cookie cookie:cookies) {
					try {
						if(cookie.getName().equals(User.SESSION_NAME) && !cookie.getValue().equals("0")) {
							int id = Integer.parseInt(cookie.getValue());
							User user = userService.getUser(id);
							session.setAttribute(User.SESSION_NAME, user);							
//							req.getRequestDispatcher("/WEB-INF/pages/list.jsp").forward(req, res);
//							res.sendRedirect(req.getContextPath() + "/list");
							req.getRequestDispatcher("/ListServlet").forward(req, res);
						}
						
					} catch (Exception e) {
						System.out.println(e.getMessage());
						throw new RuntimeException();
					}
				}
			}
		}
		chain.doFilter(request, response);
	}


	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
